package com.roubsite.sso.dao;

import java.sql.Types;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.roubsite.database.dao.EntityDao;
import com.roubsite.utils.StringUtils;
import com.roubsite.utils.UuidUtils;

public class SsoDao extends EntityDao implements ISsoDao {
	public String getSystemCode(String systemId) {
		String sql = "INSERT INTO RS_OAUTH_CODE (CODE, OAUTH_SYSTEM_ID, OAUTH_SYSTEM_CODE_EXPIRED, STATUS) VALUES (?, ?, ?, ?)";
		String code = UuidUtils.getUuid();
		int l = this.excute(sql, new String[] { code, systemId, CreateDate(), "1" },
				new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
		if (l > 0) {
			return code;
		}
		return null;
	}

	@SuppressWarnings("unchecked")
	@Override
	public String getUserToken(String systemId, String userId) {
		List<Map<String, Object>> list = this.query(
				"SELECT * FROM RS_OAUTH_TOKEN WHERE OAUTH_SYSTEM_ID=? AND USER_ID=?", new String[] { systemId, userId },
				new int[] { Types.VARCHAR, Types.VARCHAR });
		if (list.size() > 0) {
			return (String) list.get(0).get("OAUTH_ACCESS_TOKEN");
		} else {
			String insertSql = "INSERT INTO RS_OAUTH_TOKEN (OAUTH_ID, USER_ID, OAUTH_SYSTEM_ID, OAUTH_ACCESS_TOKEN) VALUES (?, ?, ?, ?)";
			String token = StringUtils.md5(UuidUtils.getUuid());
			this.excute(insertSql, new String[] { UuidUtils.getUuid(), userId, systemId, token },
					new int[] { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR });
			return token;
		}
	}

	@Override
	public boolean checkCode(String code, String systemId) {
		List<?> l = this.query("SELECT * FROM RS_OAUTH_CODE WHERE CODE=? AND OAUTH_SYSTEM_ID=?",
				new String[] { code, systemId }, new int[] { Types.VARCHAR, Types.VARCHAR });
		if (l.size() > 0) {
			Map m = (Map) l.get(0);
			String expired = (String) m.get("OAUTH_SYSTEM_CODE_EXPIRED");
			String now = StringUtils.getUnixDate();
			long _expired = Long.parseLong(expired);
			long _now = Long.parseLong(now);
			if (_expired > _now && "1".equals(m.get("STATUS"))) {
				return true;
			}
		}
		return false;
	}

	public Map getUserInfoByToken(String token) {
		String sql = "SELECT A.USER_ID,B.USER_NAME,B.USER_STATUS,B.CREATE_TIME FROM RS_OAUTH_TOKEN A,RS_USERS B WHERE A.USER_ID = B.USER_ID AND A.OAUTH_ACCESS_TOKEN=?";
		List l = this.query(sql, new String[] { token }, new int[] { Types.VARCHAR });
		if (l.size() > 0) {
			Map m = (Map) l.get(0);
			return m;
		}
		return new HashMap<>();
	}

	/**
	 * 时间戳+10分钟
	 * 
	 * @return
	 */
	public static String CreateDate() {
		Calendar nowTime = Calendar.getInstance();
		nowTime.add(Calendar.MINUTE, 10);
		return nowTime.getTime().getTime() + "";
	}

	public static void main(String[] args) {
		System.out.println(CreateDate());
	}
}
